package com.awspaas.user.apps.cpq.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.sdk.local.SDK;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class CPQ_GetTemplateModuleNumberWeb {

	public String getTemplateModuleNumber(UserContext userContext, String bindId, String mkbh, String id,
			String datas) {
		XSSFWorkbook workbookwl = new XSSFWorkbook();
		XSSFWorkbook workbook = new XSSFWorkbook();
		try {
			/**
			 * 获取当前项目的基本参数对应值
			 */
        	  JSONArray dataList=JSONObject.parseArray(datas);
        		Map<String, String> pMap = new HashMap<String, String>();
        		Map<String, String> nameMap = new HashMap<String, String>();
        		Map<String, String> noMap = new HashMap<>();
        		String msg="";
        		for(int i=0;i<dataList.size();i++) {
        			JSONObject jsonObject=(JSONObject) dataList.get(i);
        			String bh=(String) jsonObject.get("bh");
            		String value=(String) jsonObject.get("data");
            		String name=(String) jsonObject.get("name");
            		String dw=(String) jsonObject.get("dw");
            		pMap.put(bh, value);
            		nameMap.put(bh, name);
            		int num = i + 1;
					noMap.put(bh, "B$" + num);
                    if(msg.isEmpty()) {
                    	msg="模块参数："+name+":"+value+dw;
                    }else {
                    	msg+=msg+"、"+name+":"+value+dw;
                    }
        		}
        		/**
            	 * 将项目报价申请单中的参数信息进行对比，没有匹配上的参数将生成到项目报价申请单参数子表中
            	 */
          			List<BO> list = SDK.getBOAPI().query("BO_EU_CPQ_TEMPLATE_PARAMETER").bindId(bindId).list();
                   List<BO>   lists=new ArrayList<>();
          			if(list.size()>0) {
          				 List<String>   oldList=new ArrayList<>();
          				for (BO bo : list) {
    						String bh=bo.getString("PARMENTIER_NO");
    						oldList.add(bh);
    					}
          				
                    	for (String key : pMap.keySet()) {
    						int num=oldList.indexOf(key);
    						if(num==-1) {
    							BO bo2=new BO();
    							bo2.set("PARMENTIER_NO",key);
    							bo2.set("PARMENTIER_VALUE",pMap.get(key));
    							bo2.set("PARMENTIER_NAME",nameMap.get(key));
    							lists.add(bo2);
    						}
    					}
                    }else {
                    	for (String key : pMap.keySet()) {						
    							BO bo2=new BO();
    							bo2.set("PARMENTIER_NO",key);
    							bo2.set("PARMENTIER_VALUE",pMap.get(key));
    							bo2.set("PARMENTIER_NAME",nameMap.get(key));
    							lists.add(bo2);						
    					}
                    }
          			 /**
          			 * 判断所选的模块是否为动态计算单价模板，如果是计算出模块在当前项目中的单价。
          			 */
                	BO moduleData = SDK.getBOAPI().query("BO_EU_CPQ_TEMPLATE_PRICE_MODULE").addQuery("ID=", id).detail();
          			BO data = SDK.getBOAPI().query("BO_EU_CPQ_MODULE_MSG").addQuery("MKBM=", mkbh).detail();
          			String type = data.getString("SITRUE");// 是否动态计算单价模块
          			double MKDJ = Double.parseDouble(data.getString("MKDJ"));// 模块单价
          			double TJ = Double.parseDouble(data.getString("TJ"));// 体积
          			double ZL = Double.parseDouble(data.getString("ZL"));// 重量
          			double CLF = Double.parseDouble(data.getString("CLF"));// 材料费
          			double RGF = Double.parseDouble(data.getString("RGF"));// 人工费
          			double WXWG = Double.parseDouble(data.getString("WXWG"));// 外协费
          			double CGF = Double.parseDouble(data.getString("CGF"));// 采购费
          		    // 如果是则进行动态计算
          			if (type.equals("true")) {
          			// 计算当前模块中物料明细的数量和物料的成本价格，根据物料明细的表中的计算规则进行计算。
        				/**
        				 * 获取模块中的物料明细，遍历物料明细判断当前物料是否是需要计算的，是则通过计算规则进行计算，如果不是则不需要计算。
        				 */
        				List<BO> materials = SDK.getBOAPI().query("BO_EU_CPQ_MODULE_MSG_GRID").bindId(data.getBindId()).list();
        				/**
        				 * 计算物料数量和成本。
        				 */

        				/************************** 通过excel公式进行计算 ***********************************/
        				Map<String, BO> materMap = new HashMap<>();
        				
        				// 创建公式评估器
        				FormulaEvaluator formulaEvaluator = workbookwl.getCreationHelper().createFormulaEvaluator();
        				// 设置单元格值
        				Sheet sheet = workbookwl.createSheet("Sheet1");
        				for (int i = 0; i < dataList.size(); i++) {
        					int num = i + 1;
        					Cell cellB1 = sheet.createRow(i).createCell(1);
        					JSONObject jsonObject=(JSONObject) dataList.get(i);
                			String bh=(String) jsonObject.get("bh");
        					cellB1.setCellValue(pMap.get(bh));
        				}
        				// 将物料中的计算规则的参数替换为指定的excel参数
        				if (materials.size() > 0) {
        					for (int i = 0; i < materials.size(); i++) {
        						BO bo = materials.get(i);
        						String equation = bo.getString("WLJSGS");
        						if (!equation.equals("0")) {
        							// 获取物料数量计算公式中参数代号，如果有则将代号存放在list中
        							for (String key : pMap.keySet()) {
        								int num = equation.indexOf(key);
        								if (num > -1) {
        									equation = equation.replace(key, noMap.get(key));
        								}
        							}
        							// 计算出物料数量和当前模块的物料成本价格
        							Cell cellB1 = sheet.createRow(i).createCell(2);
        							cellB1.setCellFormula(equation);
        							formulaEvaluator.evaluateFormulaCell(cellB1);
        							// 获取公式计算结果
        							CellValue cellValue = formulaEvaluator.evaluate(cellB1);
        							System.out.println("The result of the formula is: " + cellValue.getNumberValue());
        							String price = bo.getString("DJ");
        							String zl = bo.getString("ZL");
        							String tj = bo.getString("TJ");
        							String clf = bo.getString("CLF");
        							String rgf = bo.getString("RGF");
        							String wx = bo.getString("WXWG");
        							String cgf = bo.getString("CGF");
        							double total = Double.parseDouble(price) * cellValue.getNumberValue();
        							double zltotal = Double.parseDouble(zl) * cellValue.getNumberValue();
        							double tjtotal = Double.parseDouble(tj) * cellValue.getNumberValue();
        							double clftotal = Double.parseDouble(clf) * cellValue.getNumberValue();
        							double rgftotal = Double.parseDouble(rgf) * cellValue.getNumberValue();
        							double wxtotal = Double.parseDouble(wx) * cellValue.getNumberValue();
        							double cgftotal = Double.parseDouble(cgf) * cellValue.getNumberValue();
        							// 将数量和成本价格放入物料map集合中
        							bo.set("SL", cellValue.getNumberValue());
        							bo.set("ZJ", total);
        							bo.set("ZZL", zltotal);
        							bo.set("ZTJ", tjtotal);
        							bo.set("ZCGF", clftotal);
        							bo.set("ZGSF", rgftotal);
        							bo.set("ZWX", wxtotal);
        							bo.set("ZCLF", cgftotal);        							
        						}
        						materMap.put(bo.getString("WLBM"), bo);        						
        					}
        				}
        				// 计算出模块的单价，每个物料总价相加
        				double mkPrice = 0;
        				double zzlPrice = 0;
        				double ztjPrice = 0;
        				double zcgfPrice = 0;
        				double zgsfPrice = 0;
        				double zwxPrice = 0;
        				double zclfPrice = 0;
        				for (String key : materMap.keySet()) {
        					BO bo = materMap.get(key);
        					String zjString = bo.getString("ZJ");
        					String zzlString = bo.getString("ZZL");
        					String ztjString = bo.getString("ZTJ");
        					String zcgfString = bo.getString("ZCGF");
        					String zgsfString = bo.getString("ZGSF");
        					String zwxString = bo.getString("ZWX");
        					String zclfString = bo.getString("ZCLF");
        					mkPrice = mkPrice + Double.parseDouble(zjString);
        					zzlPrice = zzlPrice + Double.parseDouble(zzlString);
        					ztjPrice = ztjPrice + Double.parseDouble(ztjString);
        					zcgfPrice = zcgfPrice + Double.parseDouble(zcgfString);
        					zgsfPrice = zgsfPrice + Double.parseDouble(zgsfString);
        					zwxPrice = zwxPrice + Double.parseDouble(zwxString);
        					zclfPrice = zclfPrice + Double.parseDouble(zclfString);
        				}
        				if (MKDJ == 0) {
        					MKDJ = mkPrice;       					  
                  			 TJ = ztjPrice;
                  			 ZL = zzlPrice;
                  			 CLF = zclfPrice;
                  			 RGF = zgsfPrice;
                  			 WXWG = zwxPrice;
                  			 CGF =zcgfPrice;
        				}
        				/************************** 通过excel公式进行计算 ***********************************/          				
          			}
          			
          			String rule = data.getString("SLJSGZ"); // 计算规则
        			/**
        			 * 计算模块数量。
        			 */
          			if (!rule.equals("0")) {
        				Map<String, BO> materMap = new HashMap<>();
        			
        				// 创建公式评估器
        				FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
        				// 设置单元格值
        				Sheet sheet = workbook.createSheet("Sheet1");
        				for (int i = 0; i < dataList.size(); i++) {
        					int num = i + 1;
        					Cell cellB1 = sheet.createRow(i).createCell(1);
        					JSONObject jsonObject=(JSONObject) dataList.get(i);
                			String bh=(String) jsonObject.get("bh");
        					cellB1.setCellValue(pMap.get(bh));
        				}
        				// 将物料中的计算规则的参数替换为指定的excel参数
        				// 获取物料数量计算公式中参数代号，如果有则将代号存放在list中
        				for (String key : pMap.keySet()) {
        					int num = rule.indexOf(key);
        					if (num > -1) {
        						rule = rule.replace(key, noMap.get(key));
        					}
        				}
        				// 计算出物料数量和当前模块的物料成本价格
        				Cell cellB1 = sheet.createRow(0).createCell(2);
        				cellB1.setCellFormula(rule);
        				formulaEvaluator.evaluateFormulaCell(cellB1);
        				// 获取公式计算结果
        				CellValue cellValue = formulaEvaluator.evaluate(cellB1);
        				System.out.println("The result of the formula is: " + cellValue.getNumberValue());
        				double number = cellValue.getNumberValue();
        				// 计算出模块数量后，需要计算出模块的管理费GLFY、制造费用ZZFY、体积TJ、重量ZL				
        				// 总成本价
        				double MKDJ_price = MKDJ;
        				double MKTotalPrice = number * MKDJ_price;
        				double zlTotalPrice = number * ZL;
        				double tjTotalPrice = number * TJ;
        				double clfTotalPrice = number * CLF;
        				double rgfTotalPrice = number * RGF;
        				double wxTotalPrice = number * WXWG;
        				double cgfTotalPrice = number * CGF;
        				//将计算好的数据放入选择的子表数据中，并更新当前数据。
        				moduleData.set("DJ",MKDJ );//模块单价
        				moduleData.set("SL", number);//模块数量
        				moduleData.set("DW", data.getString("DW"));//模块单位
        				moduleData.set("GG", data.getString("GG"));//规格
        				moduleData.set("ZJ", MKTotalPrice);//模块总价
        				moduleData.set("ZZL", zlTotalPrice);//总重量
        				moduleData.set("ZTJ", tjTotalPrice);//模块总体积
        				moduleData.set("ZCLF", clfTotalPrice);//模块总材料费
        				moduleData.set("ZRGF", rgfTotalPrice);//模块总人工费
        				moduleData.set("ZWXWG", wxTotalPrice);//模块总外协
        				moduleData.set("ZCGF", cgfTotalPrice);//模块总采购费
        				moduleData.set("ZL", ZL);//重量
        				moduleData.set("TJ", TJ);//模块体积
        				moduleData.set("CLF", CLF);//模块材料费
        				moduleData.set("RGF", RGF);//模块人工费
        				moduleData.set("WXWG", WXWG);//模块外协
        				moduleData.set("CGF", CGF);//模块采购费
        				moduleData.set("XDXH", data.getString("MKMC"));//选定型号
        				moduleData.set("MKBH", data.getString("MKBM"));//模块编码
        				moduleData.set("BZ", data.getString("BZ"));//适用备注说明
        				moduleData.set("BBH", data.getString("BBH"));//版本号
        				moduleData.set("VERSION", data.getString("VERSION"));//版本
        				moduleData.set("CSSM", msg);//参数说明
        				SDK.getBOAPI().update("BO_EU_CPQ_TEMPLATE_PRICE_MODULE", moduleData);        				
          			}
          			SDK.getBOAPI().create("BO_EU_CPQ_TEMPLATE_PARAMETER", lists, bindId, userContext.getUID());
          			ResponseObject ro = ResponseObject.newOkResponse();         			
        			return ro.toString();
		} catch (Exception e) {
	      throw  e;
		}finally {
			try {
				workbookwl.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
  			 try {
				workbook.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}  
		
	}

}
